<template>
  <app-content style="position: relative;" @cancel="close">
    <div class="h-panel-search">
      <Row type="flex" :space-x="10">
        <Cell style="line-height: 32px; padding-left: 20px">单据编号：</Cell>
        <Cell><input type="text" v-model="queryParam.number" placeholder="请输入单据编号" @keydown.enter="doSearch" style="width:200px"></Cell>
        <Cell style="line-height: 32px;">单据类型：</Cell>
        <Cell>
          <Select :datas="billTypeData" v-model="queryParam.billType" placeholder="请选择单据类型" keyName="key" titleName="title" style="width:200px"></Select>
        </Cell>
        <Cell style="line-height: 32px;">单据日期：</Cell>
        <Cell>
          <DateRangePicker v-model="queryParam.timeObj" format="YYYY-MM-DD" placeholder="开始日期"></DateRangePicker>
        </Cell>
      </Row>
      <Row type="flex" :space-x="10" style="padding-top:10px">
        <Cell style="line-height: 32px; padding-left: 20px;">是否生成：</Cell>
        <Cell>
          <Select :datas="buildFlagData" v-model="queryParam.hasBuildFlag" placeholder="请选择是否生成" keyName="key" titleName="title" style="width:200px"></Select>
        </Cell>
        <Cell>
          <Button color="primary" @click="doSearch" :style="btnStyle"> 查询</Button>
        </Cell>
      </Row>
    </div>
    <div class="h-panel" style="width: 1000px;margin: 0 auto;padding-top: 10px;">
      <div class="padding-right-left">
        <Row type="flex" :space-x="10">
          <Cell>
            <Button color="primary" style="margin-bottom: 10px" @click="buildVoucher()">生成凭证</Button>
          </Cell>
          <Cell>
            <Button style="margin-bottom: 10px" @click="billVoucherTemplate()">业务模板</Button>
          </Cell>
        </Row>
      </div>
      <div class="padding-right-left padding-bottom">
        <Table :datas="billData" @select="onSelectBill" checkbox :border="true" :height="600">
          <TableItem title="单据编号">
            <template slot-scope="{data}">
              <a @click="myHandleDetail(data)">{{data.billNo}}</a>
            </template>
          </TableItem>
          <TableItem title="单据类型" prop="newType"></TableItem>
          <TableItem title="单位信息" prop="supplierName"></TableItem>
          <TableItem title="金额" prop="changeAmount"></TableItem>
          <TableItem title="单据日期" prop="billTime"></TableItem>
          <TableItem title="是否生成" align="center" width="100">
            <template slot-scope="{data}">
              <span v-if="data.linkNo" style="color:green">已生成</span>
              <span v-if="!data.linkNo" style="color:red">未生成</span>
            </template>
          </TableItem>
        </Table>
      </div>
      <Pagination v-model="pagination" @change="currentChange" align="right"></Pagination>
    </div>
    <Modal v-model="openBillTempModal" v-bind="{closeOnMask: false, hasCloseIcon: true, hasDivider: true}">
      <div slot="header">业务模板</div>
      <Form ref="form" v-width="800" mode="single" :labelWidth="80" class="form-content">
        <Table :datas="tempData" :border="true" :height="600">
          <TableItem title="编号" prop="id" :width="80"></TableItem>
          <TableItem title="业务类型" prop="businessTypeName"></TableItem>
          <TableItem title="场景判断" prop="sceneJudgmentName"></TableItem>
          <TableItem title="借-科目" prop="debitSubjectName"></TableItem>
          <TableItem title="贷-科目" prop="creditSubjectName"></TableItem>
          <TableItem title="获取金额" prop="getPriceTypeName"></TableItem>
        </Table>
      </Form>
    </Modal>
    <!-- 表单区域 -->
    <bill-detail ref="billDetail"></bill-detail>
    <financial-detail ref="financialDetail"></financial-detail>
  </app-content>
</template>

<script>
  import { DEFAULT_COLOR } from '@/store/mutation-types'
  import { updateTheme } from '@/components/tools/setting'
  import { findBillDetailByNumber, findFinancialDetailByNumber } from '@/api/api'
  import { getPrevMonthFormatDate, getFormatDate } from '@/utils/util'
  import BillDetail from '@/components/tools/BillDetail'
  import FinancialDetail from '@/components/tools/FinancialDetail'
  import Vue from 'vue'

  export default {
    name: "VoucherBill",
    components: {
      BillDetail,
      FinancialDetail
    },
    data() {
      return {
        loading: false,
        checkAll: false,
        openBillTempModal: false,
        billData: [],
        tempData: [],
        selectedRows: [],
        queryParam: {
          number: '',
          timeObj: {
            start: getPrevMonthFormatDate(3),
            end: getFormatDate()
          },
          beginTime: '',
          endTime: '',
          billType: '',
          hasBuildFlag: '',
          currentPage: 1,
          pageSize: 10
        },
        pagination: {
          page: 1,
          size: 10,
          total: 0
        },
        billTypeData: [
          { key: '零售出库', title: '零售出库'},
          { key: '零售退货入库', title: '零售退货'},
          { key: '采购订单其它', title: '采购订单'},
          { key: '采购入库', title: '采购入库'},
          { key: '采购退货出库', title: '采购退货'},
          { key: '销售订单其它', title: '销售订单'},
          { key: '销售出库', title: '销售出库'},
          { key: '销售退货入库', title: '销售退货'},
          { key: '收入', title: '收入'},
          { key: '支出', title: '支出'},
          { key: '收款', title: '收款'},
          { key: '付款', title: '付款'},
          { key: '转账', title: '转账'},
          { key: '收预付款', title: '收预付款'}
        ],
        buildFlagData: [
          { key: '0', title: '未生成'},
          { key: '1', title: '已生成'}
        ],
        voucher: {},
        headerStyle: { background: '' },
        btnStyle: { background: '', borderColor: ''},
      }
    },
    watch: {
      checkAll(nval) {
        let data = Array.from(this.billData);
        data.forEach(val => val._checked = nval);
        this.billData = data;
      }
    },
    mounted() {
      this.primaryColor = Vue.ls.get(DEFAULT_COLOR)
      updateTheme(this.primaryColor)
      this.headerStyle.background = this.primaryColor
      this.btnStyle.background = this.primaryColor
      this.btnStyle.borderColor = this.primaryColor
    },
    created () {
      this.doSearch()
    },
    methods: {
      doSearch() {
        this.$api.voucher.getBillList({
          currentPage: this.pagination.page,
          pageSize: this.pagination.size,
          number: this.queryParam.number,
          beginTime: this.queryParam.timeObj.start,
          endTime: this.queryParam.timeObj.end,
          billType: this.queryParam.billType,
          hasBuildFlag: this.queryParam.hasBuildFlag
        }).then(({data}) => {
          let arr = data.records
          for (let i = 0; i < arr.length; i++) {
            if(arr[i].newType) {
              arr[i].newType = arr[i].newType.replaceAll('其它', '')
            }
            if(arr[i].changeAmount<0) {
              arr[i].changeAmount = 0-arr[i].changeAmount
            }
          }
          this.billData = arr
          this.pagination = {
            page: data.current,
            size: data.size,
            total: data.total
          }
        })
      },
      currentChange() {
        this.doSearch()
      },
      buildVoucher() {
        if (this.selectedRows.length) {
          this.$Confirm("确认要生成凭证吗?").then(() => {
            this.loading = true;
            this.$api.voucher.buildVoucher({billNo: this.selectedRows.map(value => value.billNo)}).then(() => {
              this.doSearch()
              //刷新凭证列表的数据
              this.$emit('refresh')
              this.$Message("生成凭证成功！")
            }).finally(() => {
              this.loading = false;
            });
          })
        } else {
          this.$Message("未选择记录！");
        }
      },
      billVoucherTemplate() {
        this.openBillTempModal = true
        this.$api.voucher.billVoucherTemplate().then(({data}) => {
          this.tempData = data || [];
        })
      },
      onSelectBill(data) {
        this.selectedRows = data
      },
      myHandleDetail(data) {
        let that = this
        let newType = data.newType.replaceAll('零售退货', '零售退货入库').replaceAll('采购退货', '采购退货出库').replaceAll('销售退货', '销售退货入库')
        if(data.fromType === 'bill') {
          findBillDetailByNumber({ number: data.billNo }).then((res) => {
            if (res && res.code === 200) {
              that.$refs.billDetail.show(res.data, newType);
              that.$refs.billDetail.title="详情";
            }
          })
        } else if(data.fromType === 'financial') {
          findFinancialDetailByNumber({ billNo: data.billNo }).then((res) => {
            if (res && res.code === 200) {
              that.$refs.financialDetail.show(res.data, newType);
              that.$refs.financialDetail.title="详情";
            }
          })
        }
      },
      close() {
        this.$emit('close')
      }
    }
  }
</script>

<style lang='less' scoped>
  .h-panel-body {
    padding: 20px;
  table {
    width: 100%;
    border-collapse: collapse;

  td {
    padding: 7px;
  }

  &.header {
     background-color: @primary-color;
     color: white;
   }
  }

  .details {
    font-size: 12px;
    margin: 15px 0;
    border: 1px solid @gray2-color;

  .actions {
    text-align: right;
    padding-right: 20px;

  span, a {
    display: none;
  }
  }

  input {
    display: none;

  &.display {
     display: inline-block;
   }
  }

  &-header {
     background-color: @gray3-color;
     color: @dark3-color;
   }

  td, th {
    border-bottom: 1px solid @gray2-color;
  }

  tr:hover:not(.details-header) {
    background-color: #dff7df;
    cursor: pointer;
  }

  &:hover {
     box-shadow: 0 0 10px 0 #dadada;
     border-color: #dadada;

  .actions {
  span, a {
    display: inline-block;
  }
  }

  input {
    display: inline-block;
  }
  }
  }
  }
</style>
